import { FastifyRequest, FastifyReply } from 'fastify';
import { Logger } from './log4j.util';

export function logger(req: FastifyRequest, reply: FastifyReply, done: () => void) {
    // 记录开始时间用于计算响应时间
    const start = Date.now();

    // 当响应完成时记录日志
    reply.raw.on('finish', () => {
        const statusCode = reply.statusCode;
        const responseTime = Date.now() - start;

        const logFormat = `-----------------------------------------------------------------------
    RequestOriginal: ${req.raw.url}
    Method: ${req.method}
    IP: ${req.ip}
    StatusCode: ${statusCode}
    ResponseTime: ${responseTime}ms
    Params: ${JSON.stringify(req.params)}
    Query: ${JSON.stringify(req.query)}
    Body: ${JSON.stringify(req.body || {})}
    -----------------------------------------------------------------------`;

        if (statusCode >= 500) {
            Logger.error(logFormat);
        } else if (statusCode >= 400) {
            Logger.warn(logFormat);
        } else {
            Logger.access(logFormat);
            Logger.log(logFormat);
        }
    });

    done();
}
